package cn.cangli.exception;


import cn.cangli.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler
    public Result handleException(Exception e) {
        log.error("程序出错啦",e);
        return Result.error("出错啦，请联系管理员");
    }

    @ExceptionHandler
    public Result handleDuplicateKeyException(DuplicateKeyException e) {
        String message = e.getCause().getMessage(); // message: (conn=109) Duplicate entry '13000000000' for key 'phone'

        Pattern pattern = Pattern.compile("Duplicate entry '(.+?)' for key '(.+?)'");
        Matcher matcher = pattern.matcher(message);

        if (matcher.find()) {
            String value = matcher.group(1);
            String key = matcher.group(2);

            switch (key) {
                case "username":
                    return Result.error("用户名已存在：" + value);
                case "phone":
                    return Result.error("手机号已存在：" + value);
                default:
                    return Result.error("字段 " + key + " 值重复：" + value);
            }
        } else {
            return Result.error("数据插入失败：" + message);
        }
    }
}
